/*
    BEEM is a videoconference application on the Android Platform.

    Copyright (C) 2009 by Frederic-Charles Barthelery,
                          Jean-Manuel Da Silva,
                          Nikita Kozlov,
                          Philippe Lago,
                          Jean Baptiste Vergely,
                          Vincent Veronis.

    This file is part of BEEM.

    BEEM is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BEEM is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with BEEM.  If not, see <http://www.gnu.org/licenses/>.

    Please send bug reports with examples or suggestions to
    contact@beem-project.com or http://dev.beem-project.com/

    Epitech, hereby disclaims all copyright interest in the program "Beem"
    written by Frederic-Charles Barthelery,
               Jean-Manuel Da Silva,
               Nikita Kozlov,
               Philippe Lago,
               Jean Baptiste Vergely,
               Vincent Veronis.

    Nicolas Sadirac, November 26, 2009
    President of Epitech.

    Flavien Astraud, November 26, 2009

*/
package com.beem.project.beem.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.io.InputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;

import org.jivesoftware.smack.util.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.util.Log;

import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;

import com.awan.adapter.DataAdapter;
import com.awan.adapter.FriendsDataAdapter;
import com.awan.controller.StickerCategoryItem;
import com.awan.controller.UserItem;
import com.awan.model.ChatDatabaseHandler;
import com.awan.ui.MultimediaList;
import com.awan.utils.Constanta;
import com.awan.utils.GeneralStatic;
import com.awan.utils.HttpUtilsPost;
import com.awan.utils.RefreshableListView;
import com.awan.utils.RefreshableListView.OnRefreshListener;
import com.beem.project.beem.R;
import com.beem.project.beem.BeemApplication;
import com.beem.project.beem.providers.AvatarProvider;
import com.beem.project.beem.service.Contact;
import com.beem.project.beem.service.LoginAsyncTask;
import com.beem.project.beem.service.Message;
import com.beem.project.beem.service.PresenceAdapter;
import com.beem.project.beem.service.aidl.IBeemRosterListener;
import com.beem.project.beem.service.aidl.IChat;
import com.beem.project.beem.service.aidl.IChatManager;
import com.beem.project.beem.service.aidl.IMessageListener;
import com.beem.project.beem.service.aidl.IRoster;
import com.beem.project.beem.service.aidl.IXmppFacade;
import com.beem.project.beem.smack.avatar.AvatarMetadataExtension.Info;
import com.beem.project.beem.ui.dialogs.builders.Alias;
import com.beem.project.beem.ui.dialogs.builders.ChatList;
import com.beem.project.beem.ui.dialogs.builders.DeleteContact;
import com.beem.project.beem.ui.dialogs.builders.ResendSubscription;
import com.beem.project.beem.utils.BeemBroadcastReceiver;
import com.beem.project.beem.utils.SortedList;
import com.beem.project.beem.utils.Status;
import com.conte.services.global;
import com.dheina.lazylist.ImageLoader;
import com.slidingmenu.lib.SlidingMenu;

import de.duenndns.ssl.MemorizingTrustManager;

/**
 * The contact list activity displays the roster of the user.
 */
public class ContactList extends Activity /*extends SlidingFragmentActivity*/implements OnClickListener{
	
	//private static final String STATE_MENUDRAWER = "com.beem.project.beem.ui.contactlist.menuDrawer";
    //private static final String STATE_ACTIVE_VIEW_ID = "com.beem.project.beem.ui.contactlist.activeViewId";

    private static final Intent SERVICE_INTENT = new Intent();
    static {
    	SERVICE_INTENT.setComponent(new ComponentName("com.beem.project.beem", "com.beem.project.beem.BeemService"));
    }

    private String TAG = getClass().getName();
    private BeemContactList mAdapterContactList = new BeemContactList();
    private BeemContactListView mAdapterContactListView = new BeemContactListView();
    private final List<String> mListGroup = new ArrayList<String>();

    /** Map containing a list of the different contacts of a given group.
     * Each list is a @{link SortedList} so there is no need to sort it again.
     * */
    private final Map<String, List<Contact>> mContactOnGroup = new HashMap<String, List<Contact>>();
    //private final BeemContactListOnClick mOnContactClick = new BeemContactListOnClick();
    private final Handler mHandler = new Handler();
    private final ServiceConnection mServConn = new BeemServiceConnection();
    private final BeemBroadcastReceiver mReceiver = new BeemBroadcastReceiver();
    private final ComparatorContactListByStatusAndName<Contact> mComparator =
	new ComparatorContactListByStatusAndName<Contact>();
    private final BeemRosterListener mBeemRosterListener = new BeemRosterListener();
    private List<Contact> mListContact;
    private String mSelectedGroup;
    private IRoster mRoster;
    private Contact mSelectedContact;
    private IXmppFacade mXmppFacade;
    private IChatManager mChatManager;
    private SharedPreferences mSettings;
    private LayoutInflater mInflater;
    private BeemBanner mAdapterBanner;
    private boolean mBinded;

    /**
     * Constructor.
     */
    public ContactList() {}

    /**
     * Callback for menu creation.
     * @param menu the menu created
     * @return true on success, false otherwise
     */
    @Override
    public final boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.contact_list, menu);
		return true;
    }
    private IChat mChat=null;
    private Contact mContact;
    private final IMessageListener mMessageListener = new OnMessageListener();
    //private MessagesListAdapter mMessagesListAdapter = new MessagesListAdapter();
    private class OnMessageListener extends IMessageListener.Stub {

		/**
		 * Constructor.
		 */
		public OnMessageListener() {
		}
	
		/**
		 * {@inheritDoc}.
		 */
		//@Override
		public void processMessage(IChat chat, final Message msg) throws RemoteException {}

		@Override
		public void stateChanged(IChat chat) throws RemoteException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void otrStateChanged(String otrState) throws RemoteException {
			// TODO Auto-generated method stub
			
		}
	
		
    }
    @Override
    public final boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
		case R.id.menu_broadcast_message:
			/*
			 * popup broadcast message
			 * 
			 * */
			final Dialog dialog = new Dialog(cntx);
	    	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.broadcast_message);
			dialog.setTitle("Broadcast a message to friend");
			dialog.show();
			
			final EditText broadcastText = (EditText)dialog.findViewById(R.id.broadcastText);
			Button sendBroadcastButton = (Button)dialog.findViewById(R.id.sendButton);
			
			sendBroadcastButton.setOnClickListener(new OnClickListener() {				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					
					String textMessage = broadcastText.getText().toString().trim();
					try {
						mChatManager = mXmppFacade.getChatManager();
					} catch (RemoteException e1) {
						// TODO Auto-generated catch block
						Log.e(TAG, "RemoteException:"+e1.getMessage());
						e1.printStackTrace();
					}
					if(mChatManager != null){
						for(int a=0; a<userList.size(); a++){
							UserItem ui = userList.get(a);
							Uri tmpUri = Uri.parse("xmpp:"+ui.username+"@"+Constanta.chatDomain);
							Contact tmpContact = new Contact(tmpUri);
							Message msgToSend = new Message(tmpContact.getJIDWithRes(), Message.MSG_TYPE_CHAT);
							msgToSend.setBody(textMessage);
							Log.e(TAG, "Message send to:"+ui.username);
							if (mChat == null) {
								try {
									mChat = mChatManager.createChat(tmpContact, mMessageListener);
									mChat.setOpen(true);
									mChat.sendMessage(msgToSend);
								} catch (RemoteException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									Log.e(TAG, "error broadcast:"+e.getMessage());
								}
							}else{
								//Log.e(TAG, "mChat != null");
								try {
									mChat.sendMessage(msgToSend);
								} catch (RemoteException e) {
									// TODO Auto-generated catch block
									Log.e(TAG, "error send message:"+e.getMessage());
									e.printStackTrace();
								}
							}
						}
						Toast.makeText(cntx, "Message Send", Toast.LENGTH_LONG).show();
					}else{
						Toast.makeText(cntx, "Message Failed to Send", Toast.LENGTH_LONG).show();
					}
					dialog.dismiss();
				}
			});
			
			return true;
	    case R.id.contact_list_menu_settings:
	    	startActivity(new Intent(this, Settings.class));
	    	return true;
	    case R.id.contact_list_menu_add_contact:
	    	startActivity(new Intent(ContactList.this, AddContact.class));
	    	return true;
	    case R.id.menu_change_status:
	    	startActivity(new Intent(ContactList.this, ChangeStatus.class));
	    	return true;
	    case R.id.contact_list_menu_chatlist:
			List<Contact> openedChats;
			try {
			    openedChats = mChatManager.getOpenedChatList();
			    Dialog chatList = new ChatList(ContactList.this, openedChats).create();
			    chatList.show();
			} catch (RemoteException e) {
			    e.printStackTrace();
			}
			return true;
	    case R.id.menu_disconnect:
	    	stopService(SERVICE_INTENT);
	    	System.exit(0);
	    	//finish();
	    	return true;
	    default:
	    	return false;
	}
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.contactlist_context, menu);
		//AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		//Contact c = mListContact.get(info.position);		
		String username = userList.get(onListPosition).username.toString();	
		
		Log.e(TAG," username "+username+"@"+Constanta.chatDomain+"  mRoster="+mRoster);
		
		try {
		    //mSelectedContact = mRoster.getContact(c.getJID());
			
			if(mRoster==null)
				mRoster = mXmppFacade.getRoster();
			
			mSelectedContact = mRoster.getContact(username+"@"+Constanta.chatDomain);
			Log.e(TAG," pop up delete "+mSelectedContact);
		} catch (Exception e) {
			Log.e(TAG," pop up error "+e);
		}
		//menu.setHeaderTitle(mSelectedContact.getJID().replace("@"+Constanta.chatDomain, "")+" chat option");
		menu.setHeaderTitle(username+" chat option");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
		Intent in;
		boolean result;
		if (mSelectedContact != null) {
		    switch (item.getItemId()) {
			case R.id.contact_list_context_menu_chat_item:
				Log.e(TAG,"chat onListPosition"+onListPosition);
				UserItem ui = userList.get(onListPosition);
				Uri tmpUri = Uri.parse("xmpp:"+ui.username+"@"+Constanta.chatDomain);
				Intent i = new Intent(ContactList.this, Chat.class);
				
				Bundle clipBundle=new Bundle();
				clipBundle.putString("avatarurl", Constanta.apiPath+"/"+userList.get(onListPosition).avatar);
				clipBundle.putString("jid", ui.username);
				i.putExtra("data", clipBundle);	
				
				i.setData(tmpUri);
				startActivity(i);
				
			   /* List<String> res = mSelectedContact.getMRes();
			    Log.e(TAG,"chat res"+res);
			    if (res.isEmpty()) {
			    	result = false;
			    	break;
			    }
			    for (String resv : res) {
			    	in = new Intent(this, Chat.class);
			    	in.setData(mSelectedContact.toUri(resv));				 
			    	item.getSubMenu().add(resv).setIntent(in);
			    	startActivity(in);
			    }*/
			    result = true;
			    break;
			case R.id.contact_list_context_menu_call_item:
				try {
					
					mXmppFacade.call(mSelectedContact.getJID() + "/psi");
					result = true;
			    } catch (RemoteException e) {
			    	e.printStackTrace();
			    }
			    result = true;
			    break;
			case R.id.contact_list_context_menu_user_info:
			    item.getSubMenu().setHeaderTitle(mSelectedContact.getJID());
			    result = true;
			    break;
			case R.id.contact_list_context_menu_userinfo_alias:
			    Dialog alias = new Alias(ContactList.this, mRoster, mSelectedContact).create();
			    alias.show();
			    result = true;
			    break;
			case R.id.contact_list_context_menu_userinfo_group:
			    in = new Intent(this, GroupList.class);
			    in.putExtra("contact", mSelectedContact);
			    startActivity(in);
			    result = true;
			    break;
			case R.id.contact_list_context_menu_userinfo_subscription:
			    Dialog subscription = new ResendSubscription(ContactList.this,
				mXmppFacade, mSelectedContact).create();
			    subscription.show();
			    result = true;
			    break;
			case R.id.contact_list_context_menu_userinfo_block:
			    result = true;
			    break;
			case R.id.contact_list_context_menu_userinfo_delete:
			    Dialog delete = new DeleteContact(ContactList.this, mRoster, mSelectedContact).create();
			    delete.show();
			    result = true;
			    break;
			default:
			    result = super.onContextItemSelected(item);
			    break;
		    }
		    return result;
		}
		return super.onContextItemSelected(item);
    }
    
    public static RefreshableListView listViewDefault;
    public static GridView listView;
    public static LinearLayout listParent;
    public static boolean menuIsOpen = false;
    
	public static boolean tutupMenu=false;
	
	protected ListFragment mFrag;
	protected ListFragment mRightFrag;
	private  LinearLayout flyingMenu;
	private Contact c;
    
    private boolean gridIsOn = true;
    private ImageView gridOrListImage;
    public static ImageView userAvatar;
    public static TextView profileTitle;
    
    public static Context cntx=null;
    public static Activity act;
    
    public static ImageLoader imageLoader;
    
    String currentUserJID;
    
    public static ArrayList<UserItem> userList;
    private UserListAdapter userAdapter;
    
    private int page = 1;
	private int limit = 8;
	private Dialog loadingDialog;
	
	static ListView rightListView;
	static ListView leftListView;
	private static FriendsDataAdapter rightAdapter;
	private static DataAdapter leftAdapter;
	
    protected Info selectAvatar(List<Info> available) {
    	return available.get(0);
    }
    private ChatDatabaseHandler db;
    private int onListPosition=0;
    SlidingMenu menu;
    
    
    private BroadcastReceiver mSslReceiver;
	private AsyncTask<IXmppFacade, Integer, Boolean> mTask;
	private static final int RECEIVER_PRIORITY = 50;
	private final ServiceConnection loginServConn = new LoginServiceConnection();
	private boolean lmBinded;
	private int windowsWidth;
	private int windowHeight;
    private BeemApplication session;
    
    //conte 
    private int gridClickpos;
    
	@Override
	public void onCreate(Bundle saveBundle) {
		
		super.onCreate(saveBundle);	
		
		Bundle b=getIntent().getBundleExtra("login_data");
		if(b!=null){
			boolean isMinimize = b.getBoolean("is_minimize");
			if(isMinimize){
				Log.e(getClass().getSimpleName(), "minimize");
				//moveTaskToBack(true);
				/*Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_HOME);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);*/
			}
		}
		
		Constanta.setUserData(this);
		
		session=((BeemApplication) getApplicationContext());
		cntx = this;
		act=this;
		db = new ChatDatabaseHandler(this);
		imageLoader = new ImageLoader(this);
		
		windowsWidth = getWindow().getWindowManager().getDefaultDisplay()
				.getWidth();
		windowHeight = getWindow().getWindowManager().getDefaultDisplay()
				.getHeight();
		
		menu = new SlidingMenu(this);
		menu.setMode(SlidingMenu.LEFT_RIGHT);
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		menu.setFadeEnabled(false);
		//menu.setFadeDegree(0.35f);
		menu.setShadowDrawable(R.drawable.shadow);
		menu.setShadowWidth(2);
		
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        menu.setMenu(R.layout.left_list);
        menu.setBehindWidth((windowsWidth*3)/4);
        menu.setSecondaryMenu(R.layout.right_menu);
        menu.setSecondaryShadowDrawable(R.drawable.shadow);
		
       init();
    }
	ImageView upImage, downImage;
	
	/*
	 * contesso modif
	 * start
	 */
	
	private void init(){
		Log.e(TAG,"init ui");
		/*if (saveBundle != null) {
	        mActiveViewId = saveBundle.getInt(STATE_ACTIVE_VIEW_ID);
	    }*/
	
	mSettings = PreferenceManager.getDefaultSharedPreferences(this);
    
    /*
     * left menu
     * */
	
	
	
    leftListView = (ListView)findViewById(R.id.sidebar_list);
    leftListView.setOnItemClickListener(new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			if(arg2==4){
				menu.showSecondaryMenu();
			}else if(arg2==1){
				if( DataAdapter._requestData != null ){
					
					JSONObject jsonResponse;
					try {
						
						jsonResponse = new JSONObject(DataAdapter._requestData);
						String status = jsonResponse.getString("STATUS");
						
						if(status.trim().equalsIgnoreCase("SUCCESS")){
							
							final String friendRequestrelCodeList[];
							String friendRequestUserNameList[];
							String friendRequestFullNameList[];
							
							JSONArray users = new JSONArray(jsonResponse.getString("DATA"));
							
							friendRequestrelCodeList = new String[users.length()];
							friendRequestUserNameList = new String[users.length()];
							friendRequestFullNameList = new String[users.length()];
							
							for (int i=0; i<users.length(); i++) {
								
								JSONObject jObj = users.getJSONObject(i);
								
								String relCode = jObj.getString("rel_code");
								String userName = jObj.getString("username");
								String fullName = jObj.getString("fullname");
								
								friendRequestrelCodeList[i] = relCode;
								friendRequestUserNameList[i] = userName;
								friendRequestFullNameList[i] = fullName;
								
							}
							
							final Dialog dialog = new Dialog(cntx);
					    	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
							dialog.setContentView(R.layout.right_menu_action);
							dialog.setTitle("Friend Request List");
							
							ListView actionList = (ListView)dialog.findViewById(R.id.rightMenuActionList);
							actionList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
							actionList.setAdapter(new ArrayAdapter<String>(cntx, R.layout.listview_list, friendRequestFullNameList));
							dialog.show();
							
							actionList.setOnItemClickListener(new OnItemClickListener() {
								@Override
								public void onItemClick(
										AdapterView<?> arg0, View arg1,
										final int arg2, long arg3) {
									// TODO Auto-generated method stub
									new Thread(){
										public void run(){
											String myName = mSettings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
											myName = myName.replace("@"+Constanta.chatDomain, "");
											
											Map<String, String> formParameters = new HashMap<String, String>();		
						            		formParameters.put("username", myName);
						            		formParameters.put("rel_code", friendRequestrelCodeList[arg2]);
						            		try {
												String approveRequest = HttpUtilsPost.post(Constanta.apiFriendApprove, Constanta.requestHeaders(), formParameters, null);
												JSONObject jsonResponse = new JSONObject(approveRequest);
												final String status = jsonResponse.getString("STATUS");
												final String msg = jsonResponse.getString("MESSAGE");
												runOnUiThread(new Runnable() {														
													@Override
													public void run() {
														// TODO Auto-generated method stub
														Toast.makeText(cntx, status+":"+msg, Toast.LENGTH_LONG).show();
														setLeftAndRightMenuAdapter();
														getUserList();
													}
												});
												
											} catch (MalformedURLException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											} catch (ProtocolException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											} catch (IOException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}
											//setLeftAndRightMenuAdapter();
						            		catch (JSONException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}
										}
									}.start();
									dialog.dismiss();
									//
								}
							});
							
						}else{
							Toast.makeText(cntx, "There is no friend request.", Toast.LENGTH_LONG).show();
						}
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
			}
		}
	});
    
    /*
     * get left current user profile Holder
     * */
    userAvatar = (ImageView)findViewById(R.id.user_avatar);
    userAvatar.setOnClickListener(new OnClickListener() {		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(ContactList.this, ChangeStatus.class);
			startActivity(intent);
		}
	});
    String tmpUserAvatar = mSettings.getString(Constanta.USER_AVATAR_KEY, null);
    if(tmpUserAvatar!=null)
    	imageLoader.DisplayImage(tmpUserAvatar, userAvatar);
    
    profileTitle = (TextView)findViewById(R.id.profile_title);
    TextView profileName = (TextView)findViewById(R.id.profile_name);
    
    /*
     * get left current user profile Data
     * */
    currentUserJID = mSettings.getString(Constanta.USER_FULLNAME_KEY, null);       
    String userStatus = mSettings.getString(BeemApplication.STATUS_TEXT_KEY, null);

    /*
     * set left current user profile Holder
     * */
    profileName.setText(currentUserJID);        
    profileTitle.setText(userStatus);	
    
    //mRightMenuDrawer.getMenuDrawer().peekDrawer();
    //mLeftMenuDrawer.getMenuDrawer().peekDrawer();
	
	setContentView(R.layout.contactgrid);
	
	loadingDialog = GeneralStatic.getDialogProgress(this);
	
	rightSlideMenuImage = (ImageView)findViewById(R.id.gambarMenuKanan);
	rightSlideMenuImage.setOnClickListener(this);
	
	leftSlideMenuImage = (ImageView)findViewById(R.id.gambarMenuKiri);
	leftSlideMenuImage.setOnClickListener(this);
	
	//progressBar = (ProgressBar)findViewById(R.id.contactLoading);
	
	
	
	flyingMenu = (LinearLayout)findViewById(R.id.parentFlyingMenu);	
	listParent = (LinearLayout)findViewById(R.id.listparent);
	
	this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED));				
	
	mInflater = getLayoutInflater();
	mAdapterBanner = new BeemBanner(mInflater, mListGroup);
	
	mListContact = new ArrayList<Contact>();
	listView = (GridView) findViewById(R.id.contactlist);
	userList = new ArrayList<UserItem>();
	userAdapter=new UserListAdapter(this, this, R.layout.contactlistongrid, userList);
	listView.setAdapter(userAdapter);
	registerForContextMenu(listView);
	
	listView.setOnItemLongClickListener(new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
			Toast.makeText(ContactList.this, "pos"+arg2, Toast.LENGTH_LONG).show();
			Log.e(TAG,"onItemLongClick grid pos "+arg2+" arg2 "+arg2+" arg3 "+arg3);
			onListPosition=arg2;
			return false;
		}
	});
	
	listView.setOnItemClickListener(new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			
			UserItem ui = userList.get(arg2);
			Uri tmpUri = Uri.parse("xmpp:"+ui.username+"@"+Constanta.chatDomain);
			Intent i = new Intent(ContactList.this, Chat.class);
			
			Bundle clipBundle=new Bundle();
			clipBundle.putString("avatarurl", Constanta.apiPath+"/"+userList.get(arg2).avatar);
			clipBundle.putString("jid", ui.username);
			i.putExtra("data", clipBundle);	
			
			i.setData(tmpUri);
			startActivity(i);				
		}
	});
	listView.setOnScrollListener(new OnScrollListener() {
		int lastVisual=0;
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			int vis=(firstVisibleItem+1)+visibleItemCount;
			//Log.e(TAG, "firstVisibleItem:"+firstVisibleItem);
			if(firstVisibleItem!=0){
				//balikinListView();
			}else{
				//geserListView();
			}
			if (vis > totalItemCount) {
				if (vis!=lastVisual) {
					lastVisual=vis;	
					getUserList();
				}
			}
		}
	});
	
	/*
	 * right menu ================================================================================================================================================
	 * */
	//rightAdapter = new FriendsDataAdapter(this, this);
	//mRightMenuDrawer = new MenuDrawerManager(this, MenuDrawer.MENU_DRAG_WINDOW, MenuDrawer.MENU_POSITION_RIGHT);
    //mRightMenuDrawer.setMenuView(R.layout.right_menu);
    rightListView = (ListView)findViewById(R.id.sidebar_list2);
    //rightListView.setAdapter(rightAdapter);        
    rightListView.setOnItemClickListener(new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			String ui = FriendsDataAdapter.privateFriend[arg2];
			Uri tmpUri = Uri.parse("xmpp:"+ui);
			Intent i = new Intent(ContactList.this, Chat.class);
			
			Bundle clipBundle=new Bundle();
			clipBundle.putString("avatarurl", FriendsDataAdapter.userAvatar[arg2]);
			clipBundle.putString("jid", FriendsDataAdapter.privateFriend[arg2].replace("@"+Constanta.chatDomain, ""));
			i.putExtra("data", clipBundle);	
			
			i.setData(tmpUri);
			startActivity(i);	
		}
	});
    rightListView.setOnItemLongClickListener(new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				final int pos, long arg3) {
			// TODO Auto-generated method stub
			final Dialog dialog = new Dialog(ContactList.this);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.right_menu_action);
			dialog.setTitle("Choose an Action");				
			ListView actionList = (ListView)dialog.findViewById(R.id.rightMenuActionList);
			actionList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			actionList.setAdapter(new ArrayAdapter<String>(ContactList.this, R.layout.listview_list, Constanta.rightActionTitle));
			actionList.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					switch(arg2){
					case 0:
						/*
						 * chat to selected user
						 * */
						dialog.dismiss();
						String ui = FriendsDataAdapter.privateFriend[pos];
						Uri tmpUri = Uri.parse("xmpp:"+ui);
						Intent i = new Intent(ContactList.this, Chat.class);							
						Bundle clipBundle=new Bundle();
						clipBundle.putString("avatarurl", FriendsDataAdapter.userAvatar[pos]);
						clipBundle.putString("jid", FriendsDataAdapter.privateFriend[pos].replace("@"+Constanta.chatDomain, ""));
						i.putExtra("data", clipBundle);								
						i.setData(tmpUri);													
						startActivity(i);							
						break;
					case 1:
						/*
						 * delete recent chat on selected user
						 * */
						db.deleteRecentChat(FriendsDataAdapter.privateFriend[pos]);
						dialog.dismiss();
						doRefresh();
						break;
					}
				}
			});
			dialog.show();
			return false;
		}
	});
    ImageView rightSettingMenu = (ImageView)findViewById(R.id.rightSettingMenu);
    rightSettingMenu.setOnClickListener(new View.OnClickListener() {			
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			startActivity(new Intent(ContactList.this, Settings.class));
		}
	});
    ImageView rightAddMenu = (ImageView)findViewById(R.id.rightAddMenu);
    rightAddMenu.setOnClickListener(new OnClickListener() {			
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			startActivity(new Intent(ContactList.this, AddContact.class));
		}
	});
    
    ImageView deleteAllRecentChat = (ImageView)findViewById(R.id.deleteAllRecentChatImageView);
    deleteAllRecentChat.setOnClickListener(new OnClickListener() {			
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			new AlertDialog.Builder(ContactList.this)
	        .setIcon(android.R.drawable.ic_dialog_alert)
	        .setTitle("Confirmation")
	        .setMessage("R U Really want to delete all recent chat?")
	        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	            @Override
	            public void onClick(DialogInterface dialog, int which) {

	                //Stop the activity
	                //YourClass.this.finish();    
	            	db.deleteAllRecentChat();
	            	doRefresh();
	            }

	        })
	        .setNegativeButton("No", null)
	        .show();
		}
	});
    
    /*
     * end right menu ============================================================================================================================================
     * */
	
	/*listView.setAdapter(mAdapterContactList);
	listView.setOnItemClickListener(mOnContactClick);*/
	
	listViewDefault = (RefreshableListView) findViewById(R.id.contactlistview);
	//listViewDefault.setOnItemClickListener(mOnContactClick);
	//registerForContextMenu(listViewDefault);
	listViewDefault.setAdapter(new UserListViewAdapter(this, this, R.layout.contactlistviewrow, userList));
	//listViewDefault.setAdapter(mAdapterContactListView);		
	listViewDefault.setOnScrollListener(new OnScrollListener() {
		int lastVisual=0;
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			int vis=(firstVisibleItem+1)+visibleItemCount;
			if (vis > totalItemCount) {
				if (vis!=lastVisual) {
					lastVisual=vis;	
					getUserList();
				}
			}
		}
	});
	listViewDefault.setOnItemClickListener(new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			UserItem ui = userList.get(arg2);
			Uri tmpUri = Uri.parse("xmpp:"+ui.username+"@"+Constanta.chatDomain);
			Intent i = new Intent(ContactList.this, Chat.class);
			
			Bundle clipBundle=new Bundle();
			clipBundle.putString("avatarurl", Constanta.apiPath+"/"+userList.get(arg2).avatar);
			clipBundle.putString("jid", ui.username);
			i.putExtra("data", clipBundle);	
			
			i.setData(tmpUri);
			startActivity(i);				
		}
	});
	listViewDefault.setOnRefreshListener(new OnRefreshListener() {			
		@Override
		public void onRefresh(RefreshableListView listView) {
			// TODO Auto-generated method stub
			limit=8;
			getUserList();
		}
	});
	
	if(windowsWidth==800 && windowHeight==1232){
		listView.setNumColumns(9);
	}else if(windowsWidth==800 && windowHeight==1280){
		listView.setNumColumns(5);
	}else if(windowsWidth==600 && windowHeight==976){
		listView.setNumColumns(8);
	}else if(windowsWidth==768 && windowHeight==976){
		listView.setNumColumns(9);
	}
	
	ImageView searchImage = (ImageView)findViewById(R.id.imageView5);
	searchImage.setOnClickListener(new View.OnClickListener() {			
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(menuIsOpen){
				Toast.makeText(ContactList.this, "Search Menu", Toast.LENGTH_SHORT).show();
				//balikinListView();
			}				
		}
	});
	
	ImageView contactImage = (ImageView)findViewById(R.id.imageView6);
	contactImage.setOnClickListener(new View.OnClickListener() {			
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(menuIsOpen){
				Toast.makeText(ContactList.this, "Contact Menu", Toast.LENGTH_SHORT).show();
				//balikinListView();
			}
		}
	});
	
	ImageView multimediaImage = (ImageView)findViewById(R.id.imageView7);
	multimediaImage.setOnClickListener(new View.OnClickListener() {			
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(menuIsOpen){
				//Toast.makeText(ContactList.this, "Multimedia Menu", Toast.LENGTH_SHORT).show();
				Intent multimediaIntent = new Intent(ContactList.this, MultimediaList.class);
				startActivity(multimediaIntent);
				//balikinListView();
			}
		}
	});
	
	ImageView chatImage = (ImageView)findViewById(R.id.imageView8);
	chatImage.setOnClickListener(new View.OnClickListener() {			
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(menuIsOpen){
				List<Contact> openedChats;
				try {
				    openedChats = mChatManager.getOpenedChatList();
				    //Log.d(TAG, "opened chats = " + openedChats);
				    Dialog chatList = new ChatList(ContactList.this, openedChats).create();
				    chatList.show();
				} catch (RemoteException e) {
				    e.printStackTrace();
				}
				//Toast.makeText(ContactList.this, "Chat Menu", Toast.LENGTH_SHORT).show();
				//balikinListView();
			}
		}
	});
	
	gridOrListImage = (ImageView)findViewById(R.id.imageView9);
	gridOrListImage.setOnClickListener(new View.OnClickListener() {			
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(menuIsOpen){	
				if(gridIsOn){
					listView.setVisibility(View.GONE);
					listViewDefault.setVisibility(View.VISIBLE);
					gridIsOn=false;
					gridOrListImage.setImageResource(R.drawable.gridview_icon);						
				}else{
					listViewDefault.setVisibility(View.GONE);
					listView.setVisibility(View.VISIBLE);
					gridIsOn=true;
					gridOrListImage.setImageResource(R.drawable.listview_icon);
				}
				//balikinListView();
			}
		}
	});		
	
	upImage = (ImageView)findViewById(R.id.triup);
	downImage = (ImageView)findViewById(R.id.tridown);
	
	RelativeLayout upMenuButton = (RelativeLayout)findViewById(R.id.slideMenuButton);
	upMenuButton.setOnClickListener(new View.OnClickListener() {			
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(!menuIsOpen){
				geserListView();
				menuIsOpen=true;
			}else if(menuIsOpen){
				balikinListView();
				menuIsOpen=false;
			}
			
		}
	});		
	geserListView();
	}
	
	@Override
	public void onStart() {
		
		super.onStart();
		
		//Log.e(TAG, "on start");
		session.setPage("ContactList");
		// setting class
		
		mSslReceiver = new BroadcastReceiver() {
			public void onReceive(Context ctx, Intent i) {
				try {
					//Log.i(TAG, "Interception the SSL notification");
					PendingIntent pi = i
							.getParcelableExtra(MemorizingTrustManager.INTERCEPT_DECISION_INTENT_LAUNCH);
					pi.send();
					abortBroadcast();
				} catch (PendingIntent.CanceledException e) {
					//Log.e(TAG, "Error while displaying the SSL dialog", e);
				}
			}
		};

		if (mTask == null)
			mTask = new LoginTask();
		if (!lmBinded)
			lmBinded = bindService(ContactList.SERVICE_INTENT, loginServConn,
					BIND_AUTO_CREATE);
		IntentFilter filter = new IntentFilter(
				MemorizingTrustManager.INTERCEPT_DECISION_INTENT + "/"
						+ getPackageName());
		filter.setPriority(RECEIVER_PRIORITY);
		registerReceiver(mSslReceiver, filter);
		
		
		
	}

	
	private class LoginTask extends LoginAsyncTask {

	
		LoginTask() {}

		
		protected void onPostExecute(Boolean result) {
			
			Log.e(getClass().getName(), "onPostExecute = "+result);			
			
			if (result == null || !result) { // Task cancelled or exception
				
				
				Log.e(getClass().getName(), "onPostExecute = result null");
				
			} else {
				Log.e(getClass().getName(), "onPostExecute = result ok");
				
			}
		}

		protected void onProgressUpdate(Integer... values) {
			Log.e(getClass().getName(),
					"onProgressUpdate "
							+ getResources().getStringArray(
									R.array.loganim_state)[values[0]]);
			
		}

		
		 
		protected void onCancelled() {
			super.onCancelled();
			
		}

	}
	
	
	private class LoginServiceConnection implements ServiceConnection {

		
		public LoginServiceConnection() {
		}

		// @Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mXmppFacade = IXmppFacade.Stub.asInterface(service);
			if (mTask.getStatus() == AsyncTask.Status.PENDING)
				mTask = mTask.execute(mXmppFacade);
			
			
		}

		// @Override
		public void onServiceDisconnected(ComponentName name) {
			mXmppFacade = null;
		}
	}
	
	
	public static void refresh() {
		Intent i = new Intent(cntx, ContactList.class);  //your class
	    cntx.startActivity(i);
	    act.finish();
		//((Activity) cntx).onRestart();
	}
	
	/*
	 * contesso modif
	 * end
	 */
	
	
	

	private void getUserList(){
		
		loadingDialog.show();
		imageLoader.clearCache();
		imageLoader.clearMemoryCache();

		new Thread(){
			public void run(){
				try {
					
					String myName = mSettings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
					myName = myName.replace("@"+Constanta.chatDomain, "");
					
					//String getUserList = Constanta.apiUserList;
					String getUserList = Constanta.apiUserList;//apiFriendList;
					Map<String, String> formParameters = new HashMap<String, String>();		
					formParameters.put("username", myName);	
					
					formParameters.put("page", String.valueOf(page));
					formParameters.put("limit", String.valueOf(limit));
					
					limit = limit + limit;
					//page++;
					final String profileRequest = HttpUtilsPost.post(getUserList, Constanta.requestHeaders(), formParameters, null);
					//Log.e(TAG,"getUserList="+getUserList+"\nprofileRequest="+profileRequest);
					
					runOnUiThread(new Runnable() {						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							List<UserItem> userItems = UserItem.fromJsonArrayString(profileRequest);
							userAdapter.clear();
							for (UserItem ui:userItems) {
								userAdapter.add(ui);
							}
							userAdapter.notifyDataSetChanged();
							loadingDialog.dismiss();
						}
					});
					
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					
					runOnUiThread(new Runnable() {						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							listViewDefault.completeRefreshing();
						}
					});
					this.interrupt();					
				}
			}
		}.start();		
	}
		
	private ImageView rightSlideMenuImage;
	private ImageView leftSlideMenuImage;
	
	/*@SuppressLint("NewApi")
	@Override	
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if(menu.isMenuShowing()){
			//Log.e(TAG, "onBackPressed:menu.showContent()");
			menu.showContent();
		}else{
			//Log.e(TAG, "onBackPressed:super.onBackPressed()");
			//super.onBackPressed();
			moveTaskToBack(true);
		}
		
	}*/
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			
				if(menu.isMenuShowing()){
					menu.showContent();
				}else{
					//Log.e(TAG, "onBackPressed:super.onBackPressed()");
					//super.onBackPressed();
					//moveTaskToBack(true);
					session.setPage("off");
					Intent intent = new Intent(Intent.ACTION_MAIN);
					intent.addCategory(Intent.CATEGORY_HOME);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
				}
				return true;
			}
		return super.onKeyDown(keyCode, event);
	}
	 @Override
    protected void onRestoreInstanceState(Bundle inState) {
        super.onRestoreInstanceState(inState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }
    
    /**
     * open flying menu
     * */
    public void geserListView(){   
    	
    	downImage.setVisibility(View.INVISIBLE);
    	upImage.setVisibility(View.VISIBLE);
    	
    	//Log.e(TAG,"width = "+windowsWidth+" height = "+windowHeight);
    	
    	int paddingTop=73;
    	
    	if(windowsWidth==768 && windowHeight==976){
    		paddingTop=48;
    	}
    	if(windowsWidth==720 && windowHeight==1184){
    		paddingTop=100;
    	}
    	if(windowsWidth==800){
    		paddingTop=10;
    	}
    	if(windowsWidth==720 && windowHeight==1280){
    		paddingTop=100;
    	}
    	if(windowsWidth==800 && windowHeight==1232){
    		paddingTop=48;
    	}
    	if(windowsWidth==800 && windowHeight==1280){
    		paddingTop=100;
    	}
    	if(windowsWidth==600 && windowHeight==976){
    		paddingTop=48;
    	}
    	//galaxy chat
    	if(windowsWidth==230 && windowHeight==320){
    		paddingTop=-30;
    	}
    	
    	Animation mAnimation = new TranslateAnimation(0, 0, 0, 0/*paddingTop-65*/);
    	mAnimation.setDuration(300);
        flyingMenu.startAnimation(mAnimation);    	

    	flyingMenu.setPadding(0, paddingTop+25, 0, 0);
    	menuIsOpen=true;
		listParent.setPadding(0, paddingTop+40, 0, 0);
    }
    
    /**
     * close flying menu
     * */
    public void balikinListView(){
    	
    	downImage.setVisibility(View.VISIBLE);
    	upImage.setVisibility(View.INVISIBLE);
    	
    	Animation mAnimation = new TranslateAnimation(0, 0, 0, 0);
    	mAnimation.setDuration(300);
        flyingMenu.startAnimation(mAnimation);
    	
    	flyingMenu.setPadding(0, 0, 0, 0);
    	menuIsOpen=false;    	
		listParent.setPadding(0, 15, 0, 0);
    }
    @Override
    protected void onResume() {
		super.onResume();
		//Log.e(TAG, "onResume");
		if (!mBinded)
		    mBinded = bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	
		
		setLeftAndRightMenuAdapter();
    }
    private void setLeftAndRightMenuAdapter(){
    	/*
		 * initiate right and left menu
		 * */
		new Thread(){
			public void run(){
				try{
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub							
							rightAdapter = new FriendsDataAdapter(act, cntx);
							rightListView.setAdapter(rightAdapter);							
							final Map<String, String> formParameters = new HashMap<String, String>();		
							
							String userName = mSettings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, null).replace("@"+Constanta.chatDomain, "");
							
		            		formParameters.put("username", userName);
		            		formParameters.put("limit", "10");
		            		formParameters.put("page", "1");
		            		String categoryRequest = null;		            		
		            		try {
								categoryRequest = HttpUtilsPost.post(Constanta.apiFriendRequest, Constanta.requestHeaders(), formParameters, null);
								//Log.e(TAG, "get data adapter:"+categoryRequest);
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (ProtocolException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}finally{
								leftAdapter = new DataAdapter(act, cntx, categoryRequest);
						        leftListView.setAdapter(leftAdapter);
							}
						}
					});
				}finally{
					this.interrupt();
				}
			}
		}.start();
    }
    /**
     * {@inheritDoc}
     */
  
    @Override
    protected void onPause() {
		super.onPause();
		//Log.e(TAG,"onPause");
		/*try {
		    if (mRoster != null) {
			mRoster.removeRosterListener(mBeemRosterListener);
			mRoster = null;
		    }
		} catch (RemoteException e) {
		    //Log.d("ContactList", "Remote exception", e);
		}
		if (mBinded) {
		    unbindService(mServConn);
		    mBinded = false;
		}
		mXmppFacade = null;*/
		//imageLoader.clearCache();
    }

    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	//Log.e(TAG, "on onDestroy");
    	this.unregisterReceiver(mReceiver);
    }

    /**
     * Build and display the contact list.
     * @param group name of the contact list.
     */
    private void buildContactList(String group) {
		mListContact = mContactOnGroup.get(group);
		mSelectedGroup = group;
		//Log.d(TAG, "buildContactList for group " + group);
		mAdapterContactList.notifyDataSetChanged();
		mAdapterContactListView.notifyDataSetChanged();
    }

    /**
     * Show the groups view.
     */
    private void showGroups() {
		ViewStub stub = (ViewStub) findViewById(R.id.contactlist_stub);
		if (stub != null) {
		    View v = stub.inflate();
		    Gallery g = (Gallery) v.findViewById(R.id.contactlist_banner);
		    g.setOnItemClickListener(new OnItemClickGroupName());
		    g.setAdapter(mAdapterBanner);
		    g.setSelection(0);
		} else {
		    ((LinearLayout) findViewById(R.id.contactlist_groupstub)).setVisibility(View.VISIBLE);
		    Gallery g = (Gallery) findViewById(R.id.contactlist_banner);
		    g.setSelection(0);
		}
    }

    /**
     * Hide the groups view.
     */
    private void hideGroups() {
		View v = findViewById(R.id.contactlist_groupstub);
		if (v != null)
		    v.setVisibility(View.GONE);
    }

    /**
     * Listener on service event.
     */
    private class BeemRosterListener extends IBeemRosterListener.Stub {
		/**
		 * Constructor.
		 */
		public BeemRosterListener() {
		}
	
		/**
		 * {@inheritDoc}
		 * Simple stategy to handle the onEntriesAdded event.
		 * if contact has to be shown :
		 * <ul>
		 * <li> add him to his groups</li>
		 * <li> add him to the specials groups</>
		 * </ul>
		 */
		public void onEntriesAdded(final List<String> addresses) throws RemoteException {
		    final boolean hideDisconnected = mSettings.getBoolean(BeemApplication.SHOW_OFFLINE_CONTACTS_KEY, false);
		    for (String newName : addresses) {
			Contact contact = mRoster.getContact(newName);
			boolean visible = !hideDisconnected || Status.statusOnline(contact.getStatus());
			List<String> groups = contact.getGroups();
			if (visible) {
			    for (String group : groups) {
				if (!mListGroup.contains(group)) {
				    mListGroup.add(mListGroup.size() - 1, group);
				    List<Contact> tmplist = new SortedList<Contact>(new LinkedList<Contact>(), mComparator);
				    mContactOnGroup.put(group, tmplist);
				}
				List<Contact> contactByGroups = mContactOnGroup.get(group);
				if (mSelectedGroup.equals(group)) {
				    updateCurrentList(group, contact);
				    continue;
				}
				contactByGroups.add(contact);
			    }
	
			    // add the contact to all and no groups
			    addToSpecialList(contact);
			}
		    }
		}
	
		/**
		 * {@inheritDoc}
		 * Simple stategy to handle the onEntriesDeleted event.
		 * <ul>
		 * <li> Remove the contact from all groups</li>
		 * </ul>
		 */
		public void onEntriesDeleted(final List<String> addresses) throws RemoteException {
		    //Log.d(TAG, "onEntries deleted " + addresses);
		    for (String cToDelete : addresses) {
				Contact contact = new Contact(cToDelete);
				for (Map.Entry<String, List<Contact>> entry : mContactOnGroup.entrySet()) {
				    List<Contact> contactByGroups = entry.getValue();
				    if (mSelectedGroup.equals(entry.getKey())) {
				    	updateCurrentList(entry.getKey(), contact);
				    	continue;
				    }
				    contactByGroups.remove(contact);
				}
				cleanBannerGroup();
		    }
	
		    mHandler.post(new Runnable() {
				public void run() {
				    mSelectedGroup = getString(R.string.contact_list_all_contact);
				    mListContact = mContactOnGroup.get(mSelectedGroup);
				    mAdapterContactList.notifyDataSetChanged();
				    mAdapterContactListView.notifyDataSetChanged();
				}
		    });
		}
	
		/**
		 * {@inheritDoc}
		 * Simple stategy to handle the onEntriesUpdated event.
		 * <ul>
		 * <li> Remove the contact from all groups</li>
		 * <li> if contact has to be shown add it to his groups</li>
		 * <li> if contact has to be shown add it to the specials groups</li>
		 * </ul>
		 */
		public void onEntriesUpdated(final List<String> addresses) throws RemoteException {
		    final boolean hideDisconnected = mSettings.getBoolean(BeemApplication.SHOW_OFFLINE_CONTACTS_KEY, false);
		    for (String adr : addresses) {
				Contact contact = mRoster.getContact(adr);
				boolean visible = !hideDisconnected || Status.statusOnline(contact.getStatus());
				List<String> groups = contact.getGroups();
				for (Map.Entry<String, List<Contact>> entry : mContactOnGroup.entrySet()) {
				    List<Contact> contactByGroups = entry.getValue();
				    if (mSelectedGroup.equals(entry.getKey())) {
					updateCurrentList(entry.getKey(), contact);
					continue;
				    }
				    contactByGroups.remove(contact);
				    if (visible) {
						for (String group : groups) {
						    if (!mListGroup.contains(group)) {
							mListGroup.add(mListGroup.size() - 1, group);
							List<Contact> tmplist = new SortedList<Contact>(
							    new LinkedList<Contact>(), mComparator);
							mContactOnGroup.put(group, tmplist);
						    }
						    mContactOnGroup.get(group).remove(contact);
						}
				    }
				}
		
				// add the contact to all and no groups
				if (visible) {
				    addToSpecialList(contact);
				}
		    }
		    cleanBannerGroup();
		}
	
		/**
		 * {@inheritDoc}
		 * Simple stategy to handle the onPresenceChanged event.
		 * <ul>
		 * <li> Remove the contact from all groups</li>
		 * <li> if contact has to be shown add it to his groups</li>
		 * <li> if contact has to be shown add it to the specials groups</li>
		 * </ul>
		 */
		//@Override
		public void onPresenceChanged(PresenceAdapter presence) throws RemoteException {
		    String from = presence.getFrom();
		    final boolean hideDisconnected = mSettings.getBoolean(BeemApplication.SHOW_OFFLINE_CONTACTS_KEY, false);
		    final Contact contact = mRoster.getContact(StringUtils.parseBareAddress(from));
		    boolean visible = !hideDisconnected || Status.statusOnline(contact.getStatus());
		    List<String> groups = contact.getGroups();
		    
		    getUserList();		    
		    
		    for (Map.Entry<String, List<Contact>> entry : mContactOnGroup.entrySet()) {
			List<Contact> contactByGroups = entry.getValue();
			if (mSelectedGroup.equals(entry.getKey())) {
			    updateCurrentList(entry.getKey(), contact);
			    continue;
			}
			contactByGroups.remove(contact);
			if (visible) {
			    if (groups.contains(entry.getKey())) {
				contactByGroups.add(contact);
			    }
			}
		    }
		    if (visible) {
			addToSpecialList(contact);
		    }
		}
	
		/**
		 * Add a contact to the special list No Group and All contacts.
		 * The contact will be added if the list is not the current list otherwise
		 * the list must be modified in a Handler.
		 *
		 * @param contact the contact to add.
		 */
		private void addToSpecialList(Contact contact) {
		    List<String> groups = contact.getGroups();
		    List<Contact> list = mContactOnGroup.get(getString(R.string.contact_list_all_contact));
		    if (list != mListContact) {
		    	list.add(contact);
		    }
		    list = mContactOnGroup.get(getString(R.string.contact_list_no_group));
		    if (list != mListContact && groups.isEmpty()) {
		    	list.add(contact);
		    }
		}
	
		/**
		 * Update the current list with the status of contact.
		 *
		 * @param listName name of the current list
		 * @param contact contact to update
		 */
		private void updateCurrentList(String listName, final Contact contact) {
			
			getUserList();
			
		    final boolean hideDisconnected = mSettings.getBoolean(BeemApplication.SHOW_OFFLINE_CONTACTS_KEY, false);
		    final List<String> groups = contact.getGroups();
		    String noGroup = getString(R.string.contact_list_no_group);
		    String allGroup = getString(R.string.contact_list_all_contact);
		    final boolean add = ((!hideDisconnected || Status.statusOnline(contact.getStatus())) &&	// must show and
			(
			    (listName.equals(noGroup) && groups.isEmpty()) ||			// in no group
			    groups.contains(listName) ||					// or in current
			    listName.equals(allGroup)						// or in all
			));
		    mHandler.post(new Runnable() {
				public void run() {
				    mListContact.remove(contact);
				    if (add) {
					mListContact.add(contact);
				    }
				    mAdapterContactList.notifyDataSetChanged();
				    mAdapterContactListView.notifyDataSetChanged();
				}
		    });
	
		}
	
		/**
		 * Remove old groups on the banner.
		 * @throws RemoteException if an error occur when communicating with the service
		 */
		private void cleanBannerGroup() throws RemoteException {
		    List<String> rosterGroups = mRoster.getGroupsNames();
		    List<String> realGroups = mListGroup.subList(1, mListContact.size() - 1);
		    realGroups.retainAll(rosterGroups);
		}

    }

    /**
     * Adapter contact list.
     */
    private class BeemContactList extends BaseAdapter implements Filterable {

		private final ContactFilter mFilter;
	
		/**
		 * Constructor.
		 */
		public BeemContactList() {
		    mFilter = new ContactFilter();
		}
		
	
		/**
		 * {@inheritDoc}
		 */
		//@Override
		public int getCount() {
		    return mListContact.size();
		}
	
		/**
		 * {@inheritDoc}
		 */
		//@Override
		public Object getItem(int position) {
		    return mListContact.get(position);
		}
	
		/**
		 * {@inheritDoc}
		 */
		//
		public long getItemId(int position) {
		    return mListContact.get(position).hashCode();
		}
	
	
		/**
		 * {@inheritDoc}
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			
			View v = convertView;
		    if (convertView == null) {
		    	v = mInflater.inflate(R.layout.contactlistongrid, null);
		    }
		     c = mListContact.get(position);
		    if (mRoster != null) {
				try {
				    c = mRoster.getContact(c.getJID());
				} catch (RemoteException e) {
				    e.printStackTrace();
				}
				//Log.d(TAG, "jid:"+c);
		    }
		    bindView(v, c, position);
		    return v;
			
		    /*View v = convertView;
		    if (convertView == null) {
		    	v = mInflater.inflate(R.layout.contactlistcontact contactlistongrid, null);
		    }
		     c = mListContact.get(position);
		    if (mRoster != null) {
				try {
				    c = mRoster.getContact(c.getJID());
				} catch (RemoteException e) {
				    e.printStackTrace();
				}
				//Log.d(TAG, "jid:"+c);
		    }
		    bindView(v, c);
		    return v;*/
		    
		}
	
		//@Override
		public Filter getFilter() {
		    return mFilter;
		}
	
		/**
		 * Adapte curContact to the view.
		 * @param view the row view.
		 * @param curContact the current contact.
		 */
		private void bindView(View view, Contact curContact, int position) {
		    if (curContact != null) {
		    	TextView v = (TextView) view.findViewById(R.id.contactlistpseudo);
		    	//v.setText(curContact.getName());
			
			//v = (TextView) view.findViewById(R.id.contactlistmsgperso);
			//v.setText(curContact.getMsgState());
			
			ImageView img = (ImageView) view.findViewById(R.id.avatar);
			//String avatarId = curContact.getAvatarId();
			//int contactStatus = curContact.getStatus();
			
			
			int x = windowsWidth/4;
			
			/*if(ucup.size()>0 && ucup.size()>=position){
				
				String tmpAvatar = ucup.get(position).getAvatar();
				String tmpFullName = ucup.get(position).getFullname();
				String tmpUsername = ucup.get(position).getUserName();				
				
				if(tmpUsername.equals(curContact.getName())){
					Log.e(TAG, "pos:"+position+", API username:"+tmpUsername+", Xmpp username:"+curContact.getName());
					//imageLoader.DisplayImage(tmpAvatar, img, x, x);	
					v.setText(tmpFullName);
				}
			}*/
			
			//imageLoader.DisplayImage("http://dev.digitalbuana.com/smiles_api/user_dir/24/avatar_thumb.jpg", img, x, x);
			
			//if(contactStatus!=100){
			
			
				//@Drawable avatar = getAvatarStatusDrawable(avatarId);
				// imageLoader.DisplayImageDrawable( url,act,img);
				//@img.setImageDrawable(avatar);
			//}
			//@img.setImageLevel(contactStatus);
		    }
		}
	
		/**
		 * Get a LayerDrawable containing the avatar and the status icon.
		 * The status icon will change with the level of the drawable.
		 * @param avatarId the avatar id to retrieve or null to get default
		 * @return a LayerDrawable
		 */
		private Drawable getAvatarStatusDrawable(String avatarId) {
			Drawable avatarDrawable = null;    
		    if (avatarId != null) {
				Uri uri = AvatarProvider.CONTENT_URI.buildUpon().appendPath(avatarId).build();				
				InputStream in = null;
				try {
				    try {				    
				    	in = getContentResolver().openInputStream(uri);
						avatarDrawable = Drawable.createFromStream(in, avatarId);					
				    } finally {
					if (in != null)
					    in.close();
				    }
				} catch (IOException e) {
				    //Log.w(TAG, "Error while setting the avatar " + avatarId, e);
				}
		    }
		    if (avatarDrawable == null)
		    	avatarDrawable = getResources().getDrawable(R.drawable.no_avatar);		    
		    LayerDrawable ld = (LayerDrawable) getResources().getDrawable(R.drawable.avatar_status);
		    ld.setLayerInset(1, 80, 80, 0, 0);
		    if(windowsWidth==800 && windowHeight==1232){
		    	Bitmap bitmap = ((BitmapDrawable) avatarDrawable).getBitmap();
		    	Drawable d = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 110, 100, true));
		    	avatarDrawable=d;
		    }
		    ld.setDrawableByLayerId(R.id.avatar, avatarDrawable);
		    return ld;
		}
	
		/**
		 * A Filter which select Contact to display by searching in ther Jid.
		 */
		private class ContactFilter extends Filter {
	
		    /**
		     * Create a ContactFilter.
		     */
		    public ContactFilter() { }
	
		    @Override
		    protected Filter.FilterResults performFiltering(CharSequence constraint) {
			//Log.d(TAG, "performFiltering");
			List<Contact> result = mListContact;
			if (constraint.length() > 0) {
			    result = new LinkedList<Contact>();
			    for (Contact c : mContactOnGroup.get(mSelectedGroup)) {
				if (c.getJID().contains(constraint))
				    result.add(c);
			    }
			}
			Filter.FilterResults fr = new Filter.FilterResults();
			fr.values = result;
			fr.count = result.size();
			return fr;
		    }
	
		    @Override
		    protected void publishResults(CharSequence constraint, Filter.FilterResults  results) {
			//Log.d(TAG, "publishResults");
			List<Contact> contacts = (List<Contact>) results.values;
			mListContact = contacts;
			notifyDataSetChanged();
		    }
		}
    }

    /**
     * Adapter banner list.
     */
    private static class BeemBanner extends BaseAdapter {
	private List<String> mGroups;
	private LayoutInflater mInflater;

	/**
	 * Constructor.
	 * @param inflater the inflater use to create the view for the banner
	 * @param groups list of the differents groups to adapt
	 */
	public BeemBanner(final LayoutInflater inflater, final List<String> groups) {
	    mGroups = groups;
	    mInflater = inflater;
	}

	//@Override
	public int getCount() {
	    return mGroups.size();
	}

	//@Override
	public Object getItem(int position) {
	    return mGroups.get(position);
	}

	//@Override
	public long getItemId(int position) {
	    return position;
	}

	//@Override
	public View getView(int position, View convertView, ViewGroup parent) {
	    View v = convertView;
	    if (convertView == null) {
		v = mInflater.inflate(R.layout.contactlistongrid, null);
	    }
	    ((TextView) v).setText(mGroups.get(position));
	    return v;
	}
    }

    /**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {

		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		//@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			//Log.e(TAG,"onServiceConnected");
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    try {
			mRoster = mXmppFacade.getRoster();
			if (mRoster != null) {
			    List<String> tmpGroupList = mRoster.getGroupsNames();
			    Collections.sort(tmpGroupList);
			    mListGroup.clear();
			    mListGroup.add(getString(R.string.contact_list_all_contact));
			    mListGroup.addAll(tmpGroupList);
			    mListGroup.add(getString(R.string.contact_list_no_group));
			    assignContactToGroups(mRoster.getContactList(), tmpGroupList);
			    makeSortedList(mContactOnGroup);
			    /*
			     * tutup group list atas
			     * */
			    //if (!mSettings.getBoolean(BeemApplication.HIDE_GROUPS_KEY, false))
			    //	showGroups();
			   // else
			    	hideGroups();
			    	
			    String group = getString(R.string.contact_list_all_contact);
			    buildContactList(group);
			    mRoster.addRosterListener(mBeemRosterListener);
			   
			    mChatManager = mXmppFacade.getChatManager();
			}
		    } catch (RemoteException e) {
			e.printStackTrace();
		    }
		}
	
		//@Override
		public void onServiceDisconnected(ComponentName name) {
		    try {
			mRoster.removeRosterListener(mBeemRosterListener);
		    } catch (RemoteException e) {
			e.printStackTrace();
		    }
		    mXmppFacade = null;
		    mChatManager = null;
		    mRoster = null;
		    mListContact.clear();
		    mListGroup.clear();
		    mContactOnGroup.clear();
		    mBinded = false;
		}
	
		/**
		 * Assign the differents contact to their groups.
		 * This methods will fill the mContactOnGroup map.
		 *
		 * @param contacts list of contacts
		 * @param groupNames list of existing groups
		 */
		private void assignContactToGroups(List<Contact> contacts, List<String> groupNames) {
		    boolean hideDisconnected = mSettings.getBoolean(BeemApplication.SHOW_OFFLINE_CONTACTS_KEY, false);
		    mContactOnGroup.clear();
		    List<Contact> all = new LinkedList<Contact>();
		    List<Contact> noGroups = new LinkedList<Contact>();
		    for (String group : groupNames) {
			mContactOnGroup.put(group, new LinkedList<Contact>());
		    }
		    for (Contact c : contacts) {
			if (hideDisconnected && !Status.statusOnline(c.getStatus())) {
			    continue;
			}
			all.add(c);
			List<String> groups = c.getGroups();
			if (groups.isEmpty())
			    noGroups.add(c);
			else {
			    for (String currentGroup : groups) {
				List<Contact> contactsByGroups = mContactOnGroup.get(currentGroup);
				contactsByGroups.add(c);
			    }
			}
		    }
		    mContactOnGroup.put(getString(R.string.contact_list_no_group), noGroups);
		    mContactOnGroup.put(getString(R.string.contact_list_all_contact), all);
		}
	
		/**
		 * Make the List of the map became Insertion sorted list.
		 *
		 * @param map the map to convert.
		 */
		private void makeSortedList(Map<String, List<Contact>> map) {
		    for (Map.Entry<String, List<Contact>> entry : map.entrySet()) {
			List<Contact> l = entry.getValue();
			entry.setValue(new SortedList<Contact>(l, mComparator));
		    }
		}
    }

    /**
     * Comparator Contact by status and name.
     */
    private static class ComparatorContactListByStatusAndName<T> implements Comparator<T> {
		/**
		 * Constructor.
		 */
		public ComparatorContactListByStatusAndName() {
		}
	
		//@Override
		public int compare(T c1, T c2) {
		    if (((Contact) c1).getStatus() < ((Contact) c2).getStatus()) {
			return 1;
		    } else if (((Contact) c1).getStatus() > ((Contact) c2).getStatus()) {
			return -1;
		    } else
			return ((Contact) c1).getName().compareToIgnoreCase(((Contact) c2).getName());
		}
	    }
	
	    /**
	     * Event simple click on item of the contact list.
	     */
	    private class BeemContactListOnClick implements OnItemClickListener {
		/**
		 * Constructor.
		 */
		public BeemContactListOnClick() {}
	
		/**
		 * {@inheritDoc}
		 */
		//@Override
		public void onItemClick(AdapterView<?> arg0, View v, int pos, long lpos) {
		    Contact c = mListContact.get(pos);
		    Intent i = new Intent(ContactList.this, Chat.class);	
		    //Log.e(TAG, "c:"+c.toUri());
		    i.setData(c.toUri());
		    startActivity(i);
		}
    }

    /**
     * Event simple click on middle groupe name.
     */
    private class OnItemClickGroupName implements OnItemClickListener {
		/**
		 * Constructor.
		 */
		public OnItemClickGroupName() {
		}
	
		//@Override
		public void onItemClick(AdapterView<?> arg0, View v, int i, long l) {
		    String group = mListGroup.get(i);
		    buildContactList(group);
		}
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		if(v==rightSlideMenuImage){
			
			menu.showSecondaryMenu();
			
		}else if(v==leftSlideMenuImage){
			
			menu.showMenu();
		}
	}
	
	/*
	 * default listview adapter for contact list
	 * */
	 /**
     * Adapter contact list.
     */
    private class BeemContactListView extends BaseAdapter implements Filterable {

		private final ContactFilter mFilter;
	
		/**
		 * Constructor.
		 */
		public BeemContactListView() {
		    mFilter = new ContactFilter();
		}
	
		/**
		 * {@inheritDoc}
		 */
		//@Override
		public int getCount() {
		    return mListContact.size();
		}
	
		/**
		 * {@inheritDoc}
		 */
		//@Override
		public Object getItem(int position) {
		    return mListContact.get(position);
		}
	
		/**
		 * {@inheritDoc}
		 */
		//
		public long getItemId(int position) {
		    return mListContact.get(position).hashCode();
		}
	
	
		/**
		 * {@inheritDoc}
		 */
		//@Override
		public View getView(int position, View convertView, ViewGroup parent) {
		    View v = convertView;
		    if (convertView == null) {
			v = mInflater.inflate(R.layout.contactlistcontact, null);
		    }
		    Contact c = mListContact.get(position);
		    if (mRoster != null) {
			try {
			    c = mRoster.getContact(c.getJID());
			} catch (RemoteException e) {
			    e.printStackTrace();
			}
		    }
		    bindView(v, c);
		    return v;
		}
	
		//@Override
		public Filter getFilter() {
		    return mFilter;
		}
	
		/**
		 * Adapte curContact to the view.
		 * @param view the row view.
		 * @param curContact the current contact.
		 */
		private void bindView(View view, Contact curContact) {
		    if (curContact != null) {
			TextView v = (TextView) view.findViewById(R.id.contactlistpseudo);
			v.setText(curContact.getName());
			v = (TextView) view.findViewById(R.id.contactlistmsgperso);
			v.setText(curContact.getMsgState());
			ImageView img = (ImageView) view.findViewById(R.id.avatar);
			String avatarId = curContact.getAvatarId();
			int contactStatus = curContact.getStatus();
			Drawable avatar = getAvatarStatusDrawable(avatarId);
			img.setImageDrawable(avatar);
			img.setImageLevel(contactStatus);
		    }
		}
	
		/**
		 * Get a LayerDrawable containing the avatar and the status icon.
		 * The status icon will change with the level of the drawable.
		 * @param avatarId the avatar id to retrieve or null to get default
		 * @return a LayerDrawable
		 */
		private Drawable getAvatarStatusDrawable(String avatarId) {
		    Drawable avatarDrawable = null;
		    if (avatarId != null) {
			Uri uri = AvatarProvider.CONTENT_URI.buildUpon().appendPath(avatarId).build();
			InputStream in = null;
			try {
			    try {
				in = getContentResolver().openInputStream(uri);
				avatarDrawable = Drawable.createFromStream(in, avatarId);
			    } finally {
				if (in != null)
				    in.close();
			    }
			} catch (IOException e) {
			    Log.w(TAG, "Error while setting the avatar " + avatarId, e);
			}
		    }
		    if (avatarDrawable == null)
			avatarDrawable = getResources().getDrawable(R.drawable.no_avatar);
		    LayerDrawable ld = (LayerDrawable) getResources().getDrawable(R.drawable.avatar_status);
		    ld.setLayerInset(1, 80, 80, 0, 0);
		    ld.setDrawableByLayerId(R.id.avatar, avatarDrawable);
		    return ld;
		}
	
		/**
		 * A Filter which select Contact to display by searching in ther Jid.
		 */
		private class ContactFilter extends Filter {
	
		    /**
		     * Create a ContactFilter.
		     */
		    public ContactFilter() { }
	
		    @Override
		    protected Filter.FilterResults performFiltering(CharSequence constraint) {
			//Log.d(TAG, "performFiltering");
			List<Contact> result = mListContact;
			if (constraint.length() > 0) {
			    result = new LinkedList<Contact>();
			    for (Contact c : mContactOnGroup.get(mSelectedGroup)) {
				if (c.getJID().contains(constraint))
				    result.add(c);
			    }
			}
			Filter.FilterResults fr = new Filter.FilterResults();
			fr.values = result;
			fr.count = result.size();
			return fr;
		    }
	
		    @Override
		    protected void publishResults(CharSequence constraint, Filter.FilterResults  results) {
			//Log.d(TAG, "publishResults");
			List<Contact> contacts = (List<Contact>) results.values;
			mListContact = contacts;
			notifyDataSetChanged();
		    }
		}
    }
    
    /*
     * custome user adapter by awan :D
     * */
    class UserItemHolder {
    	
    	TextView username;
    	ImageView avatar;

    }
    public class UserListAdapter extends ArrayAdapter<UserItem> {
    	
    	private ArrayList<UserItem> items;
    	private LayoutInflater mInflater;
    	private Activity activity;

    	public UserListAdapter(Activity a, Context context, int textResourceId, ArrayList<UserItem> items) {
    		super(context,textResourceId,items);
    		this.items=items;
    		this.activity=a;
    		mInflater=LayoutInflater.from(context);
    	}
    	
    	public View getView(int arg0, View convertView, ViewGroup arg2) {
    		// TODO Auto-generated method stub
    		UserItemHolder holder;
    		if (convertView==null) {
    			convertView=mInflater.inflate(R.layout.contactlistongrid, null);
    			
    			holder=new UserItemHolder();
    			holder.username=(TextView)convertView.findViewById(R.id.contactlistpseudo);
    			holder.avatar=(ImageView)convertView.findViewById(R.id.avatar);
    			convertView.setTag(holder);
    			
    		} else {
    			holder=(UserItemHolder)convertView.getTag();
    		}
    		UserItem vi=items.get(arg0);
    		holder.username.setText(vi.username);
    		holder.avatar.setTag(vi.avatar);
    		
    		String avatarUrl = vi.avatar;
    		//imageManager.displayImage(avatarUrl, activity, holder.avatar, R.drawable.no_avatar);
    		imageLoader.DisplayImage(avatarUrl, holder.avatar, 100, 100);
    		
    		UserItem di=new UserItem();
    		di.username=vi.username;
    		di.userId=vi.userId;
    		di.fullName=vi.fullName;
    		di.gender=vi.gender;
    		di.onLine=vi.onLine;
    		di.avatar=vi.avatar;
    		
    		convertView.setTag(R.id.detailTag, di);
    		return convertView;
    	}
    	
    }
    
    public class UserListViewAdapter extends ArrayAdapter<UserItem> {
    	
    	private ArrayList<UserItem> items;
    	private LayoutInflater mInflater;
    	private Activity activity;

    	public UserListViewAdapter(Activity a, Context context, int textResourceId, ArrayList<UserItem> items) {
    		super(context,textResourceId,items);
    		this.items=items;
    		this.activity=a;
    		mInflater=LayoutInflater.from(context);
    	}
    	
    	public View getView(int arg0, View convertView, ViewGroup arg2) {
    		// TODO Auto-generated method stub
    		UserItemHolder holder;
    		if (convertView==null) {
    			convertView=mInflater.inflate(R.layout.contactlistviewrow, null);
    			
    			holder=new UserItemHolder();
    			holder.username=(TextView)convertView.findViewById(R.id.contactlistpseudo);
    			holder.avatar=(ImageView)convertView.findViewById(R.id.avatar);
    			convertView.setTag(holder);
    			
    		} else {
    			holder=(UserItemHolder)convertView.getTag();
    		}
    		UserItem vi=items.get(arg0);
    		holder.username.setText(vi.username);
    		holder.avatar.setTag(vi.avatar);
    		
    		String avatarUrl = Constanta.apiPath+"/"+vi.avatar;
    		//imageManager.displayImage(avatarUrl, activity, holder.avatar, R.drawable.no_avatar);
    		imageLoader.DisplayImage(avatarUrl, holder.avatar, 100, 100);
    		
    		UserItem di=new UserItem();
    		di.username=vi.username;
    		di.userId=vi.userId;
    		di.fullName=vi.fullName;
    		di.gender=vi.gender;
    		di.onLine=vi.onLine;
    		di.avatar=vi.avatar;
    		
    		convertView.setTag(R.id.detailTag, di);
    		return convertView;
    	}
    	
    }
	
	public static void doRefresh() {
		// TODO Auto-generated method stub
		/*
		 * reload, left and right menu
		 * */
		if(cntx!= null){
			rightAdapter = new FriendsDataAdapter(act, cntx);
			rightListView.setAdapter(rightAdapter);
			leftAdapter = new DataAdapter(act, cntx, null);
	        leftListView.setAdapter(leftAdapter);
		}
		
	}    
	
	
}
